package com.zmx.doctor.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.lcw.library.imagepicker.ImagePicker;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.GlideLoader;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 个人资料
 */
public class PersonalDataActivity extends BaseActivity {


    @BindView(R.id.goods_img)
    ImageView goodsImg;
    @BindView(R.id.text_name0)
    TextView textName0;
    private int REQUEST_SELECT_IMAGES_CODE = 1;
    private String imagePath = "",s_msg;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_data;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        textName0.setText(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.name, ""));
        Glide.with(mActivity).load(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.avatar, "")).into(goodsImg);


    }


    @OnClick(R.id.goods_img)
    public void onViewClicked() {

        ImagePicker.getInstance()
                .setTitle("选择图片")//设置标题
                .showCamera(true)//设置是否显示拍照按钮
                .showImage(true)//设置是否展示图片
                .showVideo(false)//设置是否展示视频
                .setSingleType(true)//设置图片视频不能同时选择
                .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
                .setImageLoader(new GlideLoader())//设置自定义图片加载器
                .start(mActivity, REQUEST_SELECT_IMAGES_CODE);//REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode



    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){

                case 1:
                    Toast(s_msg);
                    Glide.with(mActivity).load(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.avatar, "")).into(goodsImg);
                    break;

            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);

            for (String s : imagePaths) {

                imagePath = s;
                upload();

            }

        }
    }



    private void upload() {// selImageList 包含图片路径的list


        OkHttpClient okHttpClient = new OkHttpClient();

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM); //表单上传文件


        File file = new File(imagePath); //根据路径创建file对象
        builder.addFormDataPart("image[]", //
                file.getName(),
                RequestBody.create(MediaType.parse("image/jpeg"), file)
        );

        builder.addFormDataPart("sign", AllUtil.md5(sing(null)));
        builder.addFormDataPart("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        builder.addFormDataPart("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        builder.addFormDataPart("ts", System.currentTimeMillis() / 1000 + "");
        builder.addFormDataPart("cmd", "editAvatar");
        builder.addFormDataPart("data[]", "");

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url("http://zmx.123xk.cn/app")
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure: ", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {

                    JSONObject object = new JSONObject(response.body().string());

                    Log.e("数据","数据"+object.toString());
                    s_msg = object.getString("msg");
                    if (object.getString("code").equals("1")) {

                        MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.avatar,object.getString("data"));
                        handler.sendEmptyMessage(1);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }


}
